// +----------------------------------------------------------------------
// | CmsWing [ 网站内容管理框架 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2115 http://www.cmswing.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: arterli <arterli@qq.com>
// +----------------------------------------------------------------------
module.exports = class extends think.cmswing.center {
  async __before () {
    await super.__before();
    // 判断是否登陆
    // await this.weblogin();
    if (!this.is_login) {
      // 判断浏览客户端
      if (this.isMobile) {
        // 手机端直接跳转到登录页面
        return this.redirect('/center/public/login');
      } else {
        return this.redirect('/');
      }
    }
  }
  // 我的订单
  async indexAction () {
    const status = this.para('status') || null;
    this.assign('status', status);
    const statusMap = {
      null: {
        _complex: { xuid: this.user.uid, gongid: this.user.uid, _logic: 'OR' }
      },
      0: {//未确认
        status: 0,
        order_userid: ['!=', this.user.uid],
        _complex: [{
          xuid: this.user.uid,
          gongid: this.user.uid,
          _logic: 'OR'
        },
        {
          _complex: [
            {
              gongqueren: 0,
              xuqueren: 1
            },
            {
              gongqueren: 1,
              xuqueren: 0
            }
          ],
          _logic: 'OR'
        }
        ]
      },
      1: {//采购订单
        xuid: this.user.uid,
        yewuleixing: ['in', [0, 1]]
      },
      2: {//销售订单
        gongid: this.user.uid,
        yewuleixing: ['in', [0, 1]]
      },
      3: {//委托加工
        xuid: this.user.uid,
        yewuleixing: ['in', [2, 3]]
      },
      4: {//承接加工
        gongid: this.user.uid,
        yewuleixing: ['in', [2, 3]]
      }
    };
    const map = statusMap[status];
    const data = await this.model('order').where(map).page(this.para('page')).order('id DESC').countSelect();
    const html = this.pagination(data);
    this.assign('pagination', html);
    const statusArr = [null, 0, 1, 2, 3, 4];
    await Promise.all(statusArr.map(async(status, index) => {
      const count = await this.model('order').where(statusMap[status]).count('id');
      this.assign('status' + index, status);
      this.assign('statuscount' + index, count);
    }));
    this.assign('count', data.count);
    this.assign('list', data.data);
    this.meta_title = '我的订单';
    return this.display();
  }

  /**
     * 查看订单
     * @returns {*}
     */
  async detailAction () {
    const id = this.get('id');
    this.meta_title = '查看订单详情';

    if (this.is_login > 0) {
      // 获取发布信息
      let title = ['供方信息', '需方信息'];
      const order = await this.model('order').find(id);
      if ([0, 1].indexOf(order.yewuleixing) == -1) {
        title = ['承接方信息', '委托方信息'];
      }
      this.assign('title', title);
      this.assign('order', order);
      const url = order.tupian ? JSON.parse(order.tupian) : [];
      this.assign('url', url);
      this.active = ['/shangping?mokuaibiaoshi=' + order.mokuaibiaoshi];
      // // 登录人
      // const loginUser = await this.model('member').where({id: this.is_login}).find();
      // // 发布人信息
      // const user = await this.model('member').where({id: gongxufabu.faburen}).find();
      // if (!(loginUser.groupid == 11 && user.groupid == 11) || loginUser.id == user.id) {
      //   this.assign('user', user);
      // }
      // if (loginUser.groupid == 11 && user.groupid == 11) {
      //   if (loginUser.zhucestatus == 2) {
      //     this.assign('showLiaoJieBotton', true);
      //   } else {
      //     this.assign('showLiaoJieTiaoZhuanBotton', true);
      //   }
      // }
      // if (loginUser.groupid != user.groupid && loginUser.id != user.id) {
      //   if (loginUser.zhucestatus == 2) {
      //     this.assign('showXiaDanBotton', true);
      //   } else {
      //     this.assign('showXiaDanTiaoZhuanBotton', true);
      //   }
      // }
    } else {
      return this.redirect('/');
    }

    return this.display();
  }

  // 确认订单按钮
  async querenAction () {
    if (this.is_login > 0) {
      const id = this.post('id');
      const userId = this.is_login;
      const data = await this.model('order').where({ id: id }).find();
      if (!((data.gongqueren == 0 && data.xuqueren == 1) || (data.gongqueren == 1 && data.xuqueren == 0))) { // 有一方进行了操作后 不能再操作
        return this.fail('确认失败');
      }
      let res;
      if (userId == data.gongid) {
        res = await this.model('order').where({ id: id, gongid: userId }).update({ gongqueren: 1 });
      }
      if (userId == data.xuid) {
        res = await this.model('order').where({ id: id, xuid: userId }).update({ xuqueren: 1 });
      }
      if (!res) {
        return this.fail('确认失败');
      }
      return this.success({ name: '确认成功', url: '/center/order/index/' }, '确认成功');
    } else {
      return this.fail('确认失败');
    }
  }
  // 订单取消
  async quxiaoAction () {
    if (this.is_login > 0) {
      const id = this.post('id');
      const updateData = { remark3: this.is_login + '门户web端取消' };
      let data = await this.model('order').where({ id: id }).find();
      if (!((data.gongqueren == 0 && data.xuqueren == 1) || (data.gongqueren == 1 && data.xuqueren == 0))) { // 有一方进行了操作后 不能再操作
        return this.fail('确认失败');
      }
      if (this.is_login == data.gongid) {
        updateData.gongqueren = 2;
      }
      if (this.is_login == data.xuid) {
        updateData.xuqueren = 2;
      }
      data = await this.model('order').where({ id: id }).update(updateData);
      if (!data) {
        return this.fail('取消失败');
      }
      // const gongxufabuid = data.gongxufabuid;
      // if (!think.isEmpty(gongxufabuid)) {
      //   const fabu = await this.model('gongxufabu').where({id: gongxufabuid}).update({status: 5});
      //   if (!fabu) {
      //     return this.fail('取消失败-挂单恢复失败');
      //   }
      // }
      return this.success({ name: '取消成功', url: '/center/order/index/' }, '取消成功');
    } else {
      return this.fail('取消失败');
    }
  }

  // 删除订单
  async delorderAction () {
    let res;
    const type = this.get('type') || null;
    if (think.isEmpty(type)) {
      const map = {
        id: this.get('id'),
        user_id: this.user.uid,
        status: ['IN', [4, 6]]
      };
      res = await this.model('order').where(map).update({ is_del: 1 });
    } else {
      res = await this.model('order').where({ id: this.get('id'), user_id: this.user.uid }).delete();
    }

    if (res) {
      return this.success({ name: '删除成功！' });
    } else {
      return this.fail('删除失败!');
    }
  }

  // 确认收货
  async confirmreceiptAction () {
    const map = {
      id: this.get('id'),
      user_id: this.user.uid,
      delivery_status: 1,
      status: ['NOTIN', [4, 6]]
    };
    const res = await this.model('order').where(map).update({ status: 4 });
    if (res) {
      return this.success({ name: '操作成功！' });
    } else {
      return this.fail('操作失败!');
    }
  }
};
